package com.example.playnote.fragment

import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.example.playnote.R
import com.example.playnote.activity.login.LoginActivity
import com.example.playnote.activity.ui.ContentActivity
import com.example.playnote.adapter.TypeArticleAdapter
import com.example.playnote.base.BaseFragment
import com.example.playnote.bean.Constant
import com.example.playnote.bean.Datas
import com.example.playnote.bean.HomeListResponse
import com.example.playnote.bean.ToastFlag
import com.example.playnote.databinding.FragmentTypeContentBinding
import com.example.playnote.toasty
import com.example.playnote.utils.MMKVUtils
import com.example.playnote.viewModel.HomeViewModel


class TypeArticleFragment : BaseFragment<HomeViewModel, FragmentTypeContentBinding>(){
    /**
     * Data List
     */
    private var datas: List<Datas>? = null
    /**
     * type id
     */
    private var cid: Int = 0
    /**
     * check login for SharedPreferences
     */
    private val isLogin: Boolean by lazy {
        MMKVUtils.getBoolean(Constant.LOGIN_KEY) ?: false
    }
    /**
     * adapter
     */
    private val typeArticleAdapter: TypeArticleAdapter by lazy {
        TypeArticleAdapter(requireContext(), datas)
    }
    override fun initView(savedInstanceState: Bundle?) {
        cid = arguments?.getInt(Constant.CONTENT_CID_KEY)?:0
        mDatabind.tabSwipeRefreshLayout.run {
            isRefreshing = true
            setOnRefreshListener(onRefreshListener)
        }
        mDatabind.tabRecyclerView.run {
            layoutManager = LinearLayoutManager(activity)
            adapter = typeArticleAdapter
        }
        typeArticleAdapter.run {
            setOnLoadMoreListener(onRequestLoadMoreListener, mDatabind.tabRecyclerView)
            onItemClickListener = this@TypeArticleFragment.onItemClickListener
            onItemChildClickListener = this@TypeArticleFragment.onItemChildClickListener
            setEmptyView(R.layout.fragment_home_empty)
        }
        mViewModel.getTypeArticleList(cid = cid)
    }

    override fun lazyLoadData() {
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.typeArticleList.observe(this) {
            if (it.errorCode != 0) {
                getTypeArticleListFailed(it.errorMsg)
                return@observe
            }
            val total = it.data.total
            if (total == 0) {
                getTypeArticleListZero()
                return@observe
            }
            if (total < it.data.size) {
                getTypeArticleListSmall(it.data)
                return@observe
            }
            datas = it.data.datas
            getTypeArticleListSuccess(it.data)
        }
    }


    /**
     * get Type Article list Success
     * @param result ArticleListResponse
     */
    private fun getTypeArticleListSuccess(result: HomeListResponse) {
        result.datas.let {
            typeArticleAdapter.run {
                // 列表总数
                val total = result.total
                // 当前总数
                if (result.offset >= total || data.size >= total) {
                    loadMoreEnd()
                    return@let
                }
                if (mDatabind.tabSwipeRefreshLayout.isRefreshing) {
                    replaceData(it)
                } else {
                    addData(it)
                }
                loadMoreComplete()
                setEnableLoadMore(true)
            }
        }
        mDatabind.tabSwipeRefreshLayout.isRefreshing = false
    }

    /**
     * get Type Article list Failed
     * @param errorMessage error message
     */
    private fun getTypeArticleListFailed(errorMessage: String?) {
        typeArticleAdapter.setEnableLoadMore(false)
        typeArticleAdapter.loadMoreFail()
        requireContext().toasty(ToastFlag.ERROR, errorMessage?:getString(R.string.get_data_error))
        mDatabind.tabSwipeRefreshLayout.isRefreshing = false
    }

    /**
     * get Type Article list data size equal zero
     */
    private fun getTypeArticleListZero() {
        requireContext().toasty(ToastFlag.ERROR, getString(R.string.get_data_zero))
        mDatabind.tabSwipeRefreshLayout.isRefreshing = false
    }

    /**
     * get Type Article list data less than 20
     * @param result ArticleListResponse
     */
    private fun getTypeArticleListSmall(result: HomeListResponse) {
        result.datas.let {
            typeArticleAdapter.run {
                replaceData(it)
                loadMoreComplete()
                loadMoreEnd()
                setEnableLoadMore(false)
            }
        }
        mDatabind.tabSwipeRefreshLayout.isRefreshing = false
    }

    /**
     * add article success
     * @param result HomeListResponse
     * @param isAdd true add, false remove
     */
    fun collectArticleSuccess(result: HomeListResponse, isAdd: Boolean) {
        requireContext().toasty( ToastFlag.SUCCESS,
            if (isAdd) requireContext().getString(R.string.bookmark_success) else requireContext().getString(
                R.string.bookmark_cancel_success
            )
        )
    }

    /**
     * add article false
     * @param errorMessage error message
     * @param isAdd true add, false remove
     */
    private fun collectArticleFailed(errorMessage: String?, isAdd: Boolean) {
        requireContext().toasty( ToastFlag.ERROR,
            if (isAdd) requireContext().getString(
                R.string.bookmark_failed,
                errorMessage
            ) else requireContext().getString(R.string.bookmark_cancel_failed, errorMessage)
        )
    }

    /**
     * RefreshListener
     */
    private val onRefreshListener = SwipeRefreshLayout.OnRefreshListener {
        mDatabind.tabSwipeRefreshLayout.isRefreshing = true
        typeArticleAdapter.setEnableLoadMore(false)
        mViewModel.getTypeArticleList(cid = cid)
    }
    /**
     * ItemClickListener
     */
    private val onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
        if (datas?.isNotEmpty() == true) {
            Intent(activity, ContentActivity::class.java).run {
                putExtra(Constant.CONTENT_URL_KEY, datas!![position].link)
                putExtra(Constant.CONTENT_ID_KEY, datas!![position].id)
                putExtra(Constant.CONTENT_TITLE_KEY, datas!![position].title)
                startActivity(this)
            }
        }
    }
    /**
     * LoadMoreListener
     */
    private val onRequestLoadMoreListener = BaseQuickAdapter.RequestLoadMoreListener {
        val page = typeArticleAdapter.data.size / 20 + 1
        mViewModel.getTypeArticleList(page, cid)
    }
    /**
     * ItemChildClickListener
     */
    private val onItemChildClickListener =
        BaseQuickAdapter.OnItemChildClickListener { _, view, position ->
            if (datas?.size != 0) {
                val data = datas!![position]
                when (view.id) {
                    R.id.homeItemLike -> {
                        if (isLogin) {
                            val collect = data.collect
                            data.collect = !collect
                            typeArticleAdapter.setData(position, data)
                            mViewModel.collectArticle(data.id, !collect)
                        } else {
                            Intent(activity, LoginActivity::class.java).run {
                                startActivity(this)
                            }
                            requireContext().toasty(ToastFlag.ERROR, getString(R.string.login_please_login))
                        }
                    }
                }
            }
        }

    companion object {
        fun newInstance(cid: Int): TypeArticleFragment {
            val fragment = TypeArticleFragment()
            val args = Bundle()
            args.putInt(Constant.CONTENT_CID_KEY, cid)
            fragment.arguments = args
            return fragment
        }
    }
}